function fresh(){
       window.location.reload();//强迫浏览器刷新当前页面，默认参数为false，表示从客户端缓存里取当前页。如果指定为true,则以GET方式从服务端取最新的页面,相当于客户端点击F5。
 }
function ShowEditorByStrategy(name, code) {
	var lis = $('li[id^=li-]');
	for (var i = 0; i < lis.length; i++) {
		if (lis[i].id == ('li-' + name)) {
			return;
		}
	}
	var tabs = $("#centerTabs");
	var contents = $("#tab-content");
	//tab code
	var tab = '<li role="presentation" id="li-' + name + '" data-tabid="' + name +
		'" class="editor-tab active"><a href="#t' + name + '" aria-controls="t' + name +
		'" role="tab" data-toggle="tab" id="tab-' + name + '" style="">' + name +
		'<span aria-hidden="true"  class="span-close close-tabs" style="margin-left:10px;">×</span></a></li>';
	//get tab element
	tab = $(tab)
	var tabContent = '<div role="tabpanel" class="tab-pane fullH" id="t' + name +
		'"><div class="panel-body fullH"> <div class="panel panel-default fullH" style="border-radius: 0px"><div id="editor' +
		name + '" class="pg-editor fullH"> <textarea id="myeditor' + name +
		'" class="editor fullH" style="border-color: #DDDDDD; border-style: solid; border-width: 1px; font-size: 13px"> </textarea></div></div>  </div></div>';
	tabContent = $(tabContent)
	tabs.append(tab)
	contents.append(tabContent)
	tab.addClass('active').siblings().removeClass('active')
	tabContent.addClass('active').siblings().removeClass('active')
	var edit = initCodeMirrorEditor('myeditor' + name)
	if (code != null) {
		edit.setValue(code);
	} else {
		edit.setValue("");
	}

	tab.on('shown.bs.tab', function(e) {
		edit.refresh();
	})
	//edit.layout();
	$('.close-tabs').unbind('click').on('click', function(e) {
		var contentId = $($(this).parent()).attr("aria-controls")
		$("#" + contentId).remove()
		$(this).parent().parent().remove()
		$("#centerTabs").children().last().addClass('active')
		$("#tab-content").children().last().addClass('active')
	})
}

function removeSchemaNode(name) {
	// $('#treeStrategy').jstree(true).delete_node(name);
	var tree = [];
	for (var i = 0; i < SCHEMA.length; i++) {
		if (SCHEMA[i].id != name) {
			tree.push(SCHEMA[i]);
		}
	}
	SCHEMA = tree;
	showSchemaTree();
}

function removeStrategyNode(name) {
	// $('#treeStrategy').jstree(true).delete_node(name);
	var tree = [];
	for (var i = 0; i < STRATEGY.length; i++) {
		if (STRATEGY[i].id != name) {
			tree.push(STRATEGY[i]);
		}
	}
	STRATEGY = tree;
	showStrategyTree();
}

function showStrategyTree() {
	var tree = STRATEGY;
	//clear the prev tree
	$('#treeStrategy').jstree('destroy');
	$('#treeStrategy').data('jstree', false);

	//init with data
	$('#treeStrategy').jstree({
		'plugins': ["themes", "contextmenu"],
		"contextmenu": {
			"items": {
				"create": null,
				"rename": null,
				"remove": null,
				"ccp": null,
				"删除": {
					"label": "删除",
					"action": function(data) {
						var inst = jQuery.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if (confirm("确定要删除此策略？")) {
							removeStrategy(obj.id);
						}
					}
				}
			}
		},
		'core': { //core主要功能是控制树的形状，单选多选等等
			'data': tree,
			"multiple": false, // 单选
			'check_callback': function(operation, node, node_parent, node_position, more) {
				// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node', 'copy_node' or 'edit'
				// in case of 'rename_node' node_position is filled with the new node name
				return operation === 'delete_node' ? true : false;
			}
		}
	})
	$('#treeStrategy').on("changed.jstree", function(e, data) {
		ReqCode(data.node.id)

		//ShowEditorById(data.node.id, data.node.text);
	});
}

function freshInstrument(data) {
	var opt = $("#options");
	opt.html("");
	data = data.getInstrumentList().array;
	if (data != null && data.length > 0) {
		for (var i = 0; i < data[0].length; i++) {
			opt.append($("<option>" + data[0][i][0] + "</option>"));
			// console.log(data[0][i][0]);
		}
	}
	$('#instrumentOption').selectpicker('refresh');
}

function showSchemaTree() {
	tree = SCHEMA;
	//clear the prev tree
	$('#treeSchema').jstree('destroy');
	$('#treeSchema').data('jstree', false);

	//init with data
	$('#treeSchema').jstree({
		'plugins': ["themes", "contextmenu"],
		"contextmenu": {
			"items": {
				"create": null,
				"rename": null,
				"remove": null,
				"ccp": null,
				"删除": {
					"label": "删除",
					"action": function(data) {
						var inst = jQuery.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if (confirm("确定要删除此场景？")) {
							removeSchema(obj.id);
						}
					}
				}
			}
		},
		'core': { //core主要功能是控制树的形状，单选多选等等
			'data': tree,
			"multiple": false, // 单选
			'check_callback': function(operation, node, node_parent, node_position, more) {
				// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node', 'copy_node' or 'edit'
				// in case of 'rename_node' node_position is filled with the new node name
				return operation === 'delete_node' ? true : false;
			}
		}
	})
	$('#treeSchema').on("changed.jstree", function(e, data) {
		console.log(data.node.id);
		//ShowEditorById(data.node.id, data.node.text);
	});
}

// function saveSchema() {
// 	var start = $("#datetime-start").val();
// 	var end = $("#datetime-end").val();
// 	var schemaName = $("#schemaName").val();
// 	var schemaDuration = $("#schemaDuration").val();

// }

function showLoginDialog() {
	// $(".modal-backdrop").css("background-color","white")
	$('#loginDialog').modal('show');
	$(".modal-backdrop").css("opacity", "1");
	$(".modal-backdrop").css("background-color", "white")
}

function hideLoginDialog() {
	// $(".modal-backdrop").css("background-color","white")
	$(".modal-backdrop").css("opacity", "0.5");
	$(".modal-backdrop").css("background-color", "black")
	$('#loginDialog').modal('hide');
}
///Pad
function showSchemaCreateDialog() {
	$('#schemaCreateDialog').modal('show');
}

function saveSchema() {
	var start = $("#datetime-start").val();
	var end = $("#datetime-end").val();
	var schemaName = $("#schemaName").val();
	var schemaDuration = $("#schemaDuration").val();
	var slippage = $("#slippage").val();
	var closeTodayFee = $("#closeTodayFee").val();
	var closeFee = $("#closeFee").val();
	var initFund = $("#initFund").val();
	var inst = $("#instrumentOption").val();

	if (start == null || end == null || schemaName == null || schemaName == null || inst == null || slippage == null ||
		closeTodayFee == null ||
		closeFee == null ||
		initFund == null
	) {
		alert("参数不全")
		return;
	}
	var request = new proto.Req;
	request.setReqType(proto.RequestType.REQ_SET_SCENE);
	var s = new proto.ReqSetScene;
	s.setName(schemaName);
	var p = new proto.BtPara;

	p.setFund(initFund);
	p.setStartTradingday(start);
	p.setEndTradingday(end);
	var ipps = [];
	var c = new proto.CommissionPara
	for (var i = 0; i < inst.length; i++) {
		var ipp = new proto.InstrumentPeriodPara;
		ipp.setInstrument(inst[i]);
		ipp.setPeriod(schemaDuration);
		ipps.push(ipp);
		c.setInstrument(inst[i])
		c.setCloseTodayMoney(closeFee)
		c.setCloseTodayMoney(closeTodayFee)
	}
	p.setInstrumentPeriodList(ipps)
	s.setPara(p);
	request.setReqSetScene(s);
	if (WS != null) {
		WS.send(request.serializeBinary());
	}
	$('#schemaCreateDialog').modal('hide');
}

///
function showCreateStrategyDialog() {
	$('#createStrategyDialog').modal('show');
}

function onCreateDialogOk() {
	var templateType = 0;
	switch ($("#createDialogOptionList>.active").html()) {
		case "K线驱动型策略":
			templateType = 2;
			break;
		case "Tick驱动型策略":
			templateType = 1;
			break;
		case "空项目":
			templateType = 0;
			break;
	}
	var name = $("#createDialogInputName").val();

	for (var i = 0; i < STRATEGY.length; i++) {
		if (STRATEGY[i].id == name) {
			return;
		}
	}

	STRATEGY.push({
		"id": name,
		"parent": "#",
		"text": name
	})
	SaveCode(name + '.py', '');
	showStrategyTree();
	///
	$('#createStrategyDialog').modal('hide');
	ReqCode(name);
}
function showDeskMsg(fun,Id){
	if(window.Notification && Notification.permission !== "denied") {
	                //Notification.requestPermission这是一个静态方法，作用就是让浏览器出现是否允许通知的提示
	                Notification.requestPermission(function(status) {
	                    // console.log('2: '+status);
	                    //如果状态是同意
	                    if (status === "granted") {
	                        var m = new Notification('回测完成', {
	                            body: '请看回测报告',　　//消息体内容
	                            // icon:"images/img1.jpg"　　//消息图片
	                        });
	                        m.onclick = function () {//点击当前消息提示框后，跳转到当前页面
	                          if(fun!=null){
								   fun(Id);
							  }
	                        }
	                    } 
						// else{
	     //                    alert('当前浏览器不支持弹出消息')
	     //                }
	                });
	            }
}
function removeTask(id) {
	var request = new proto.Req;
	request.setReqType(proto.RequestType.REQ_REMOVE_BT_TASK);
	var t = new proto.ReqRemoveBtTask;
	t.setIdList([id]);
	request.setReqRemoveBtTask(t);
	if (WS != null) {
		WS.send(request.serializeBinary());
	}
}
function initTransactionPage(amt){
	console.l
	//设置页基
	TotalSize=amt;
	TotalPage=Math.ceil(amt/1000);
	CIndex=1;
	reqTransaction(ReportId,0,1000);
	//发起分页请求
}
function showTransactionPage(p){
	var tColumns = [{
			field: 'name',
			title: '合约'		
		},
		{
			field: 'price',
			title: '成交价'
		},
		{
			field: 'oc',
			title: '开平'
		},
		{
			field: 'ls',
			title: '买卖'
		},
	
		{
			field: 'vol',
			title: '头寸'
		}
	];
	var data = [];
	for(var i=0;i<p.length;i++){
		data.push(
		{
			name: p[i].getInstrument(),
			price: p[i].getPrice(),
			oc: p[i].getOffsetFlag()==48?'开':'平',
			ls: p[i].getDirection()==48?'买':'卖',
			vol: p[i].getVolume()
		});
	}
	$('#tableT').bootstrapTable('destroy'); //动态加载表格之前，先销毁表格
	
	$('#tableT').bootstrapTable({ //表格初始化
		columns: tColumns, //表头
		data: data, //通过ajax返回的数据	
		pageList: [],
		cache: false,
		striped: true,
		pagination: false,
		sidePagination: 'client',
		search: false,
		showRefresh: false,
		showExport: false			
	});	
	initPagerBar();
}
function initPagerBar(){
	
	ind=CIndex;
	var pager=$("#Pager");	
	pager.html("");

	pager.append($('<li class="page-item page-pre"><a class="page-link" aria-label="上" >‹</a></li>'));
	for(var i=1;i<=TotalPage;i++){
		if(i==ind){
			pager.append('<li class="page-item active"><a class="page-link"  href="javascript:PagerI('+i+')">'+i+'</a></li>');
		}else{
			pager.append('<li class="page-item"><a class="page-link"  href="javascript:PagerI('+i+')">'+i+'</a></li>');
		}
	}
	pager.append($('<li class="page-item page-next"><a class="page-link" aria-label="下" >›</a></li>'));
}
 
function PagerI(index){
	//ReportId
	CIndex=index;
	reqTransaction(ReportId,index*1000,1000); 
}
function reqTradePage(skip,take){
	
}
function initReport(id) {
	// alert("回测进程还在执行中");
	reqReportSummary(id);
	reqDailyIncome(id);
	reqLongIncome(id);
	reqShortIncome(id);
	reqAccountDetail(id);
	reqTransactionAmt(id);
	ReportId=id;
	// console.log('initReport:'+id);
}

function LoadDailyInComes(arr) {
	var dates = [];
	var values = [];
	for (var i = 0; i < arr.length; i++) {
		dates.push(arr[i].getTime());
		values.push(arr[i].getProfit());
	}
	ShowChart("dailyIncome", "逐日盈亏", dates, values);
}

function LoadLongInComes(arr) {
	var dates = [];
	var values = [];
	for (var i = 0; i < arr.length; i++) {
		dates.push(arr[i].getTime());
		values.push(arr[i].getProfit());
	}
	ShowChart("incomeByLong", "做多盈亏", dates, values);
}

function LoadShortInComes(arr) {
	var dates = [];
	var values = [];
	for (var i = 0; i < arr.length; i++) {
		dates.push(arr[i].getTime());
		values.push(arr[i].getProfit());
	}
	ShowChart("incomeByShort", "做空盈亏", dates, values);
}
function LoadAccountDetail(arr){
	if(arr.length<1){return;}
	var dates = [];
	var closeProfit = [];
	var balance = [];
	var available = [];
	for (var i = 1; i < arr.length; i++) {
		dates.push(arr[i].getTradingday());
		// closeProfit.push(arr[i].getCloseProfit());
		balance.push(arr[i].getAccountBalance());
		available.push(arr[i].getAccountAvailable());
	}
	if(dates.length<1){
		return;
	}
	$('#accountDetail').show();
	var option = {
	    title: {
	        text: '账户详情'
	    },
	    legend: {
	        data: [ '收盘权益', '可用资金']
	    },
	    tooltip: {
	        trigger: 'axis',
	        axisPointer: {
	            type: 'cross',
	            animation: false
	            
	        }
	    },
			dataZoom: [{
				show: true,
				start: 0,
				end: 100
			}],
	    
	    xAxis: {
	        data: dates	     
	    },
	    yAxis: {
			scale: true
	    },
	    series: [ {
	        name: '收盘权益',
	        type: 'line',
	        data: balance
	    }, {
	        name: '可用资金',
	        type: 'line',
	        data: available
	    }] 
	};
	var ct = echarts.init(document.getElementById('accountDetail'));
	ct.setOption(option);
}
function showSummary(p) {
	var table = $(
		"<table class=\"table table-striped\"><thead><tr><th>指标</th><th>值</th><th>指标</th><th>值</th><th>指标</th><th>值</th></tr></thead><tbody id=\"tbody\"></tbody></table>"
	);
	var tbody = $("#tbody", table);
	//var m = { "NetProfit": 1, "AnnualProfitRatio": 10, "PLRatio": 1, "AvgProfit": 1, "CountOfTrades": 1, "MaxDrawdownRatio": 1, "MaxDrawdownAmount": 1, "AvgDrawdownRatio": 10, "AvgDrawdownAmount": 10, "ProfitFactor": 1, "SharpRatio": 1, "InitCapital": 1, "DailyPLRatio": 1, "MaxSingleProfit": 1, "MaxCountOfComboWin": 1, "MaxRetracementInterval": 1, "MaxSingleLoss": 1, "MaxCountOfComboLoss": 1, "MaxComboProfitMoney": 1, "CountOfWinning": 1, "MaxComboLossAmount": 1, "CountOfLosses": 1, "MaxLossShare": 1, "TotalYieldRatio": 1, "TotalTradingDays": 1, "TotalLoss": 1, "CountOfWiningDate": 1, "Volatility": 1, "CountOfLossDate": 1, "DailyAvgLossAmount": 1, "MARRatio": 1, "AverageLoss": 10, "DailyAverageProfit": 1 }
	tbody.append($("<tr><td>净利润</td><td>" + p.getNetprofit() + "</td><td>年化收益率</td><td>" + p.getAnnualprofitratio() +
		"</td><td>盈亏比</td><td>" + p.getPlratio() + "</td></tr>"));
	tbody.append($("<tr><td>平均盈利额</td><td>" + p.getAvgprofit() + "</td><td>交易次数</td><td>" + p.getCountoftrades() +
		"</td><td>最大回撤比率</td><td>" + p.getMaxdrawdownratio() + "</td></tr>"));
	tbody.append($("<tr><td>最大回撤金额</td><td>" + p.getMaxdrawdownamount() + "</td><td>平均回撤比率</td><td>" + p.getAvgdrawdownratio() +
		"</td><td>平均回撤金额</td><td>" + p.getAvgdrawdownamount() + "</td></tr>"));
	tbody.append($("<tr><td>初始资金</td><td>" + p.getMaxretracementinterval() + "</td><td>夏普比率</td><td>" + p.getSharpratio() +
		"</td><td>最大连续盈利次数</td><td>" + p.getMaxcountofcombowin() + "</td></tr>"));
	tbody.append($("<tr><td>最大回撤周期</td><td>" + p.getMaxretracementinterval() + "</td><td>最大单次亏损</td><td>" + p.getMaxsingleloss() +
		"</td><td>最大连续亏损次数</td><td>" + p.getMaxcountofcomboloss() + "</td></tr>"));
	tbody.append($("<tr><td>胜率</td><td>" + p.getWinratio() + "</td><td>最大连续盈利金额</td><td>" + p.getMaxcomboprofitmoney() +
		"</td><td>盈利次数</td><td>" + p.getCountofwinning() + "</td></tr>"));
	tbody.append($("<tr><td>最大盈利占比</td><td>" + p.getMaxprofitshare() + "</td><td>最大连续亏损金额</td><td>" + p.getAnnualprofitratio() +
		"</td><td>波动率</td><td>" + p.getVolatility() + "</td></tr>"));
	tbody.append($("<tr><td>最大亏损占比</td><td>" + p.getMaxlossshare() + "</td><td>总收益率</td><td>" + p.getMaxcombolossamount() +
		"</td><td>总盈利</td><td>" + p.getTotalprofit() + "</td></tr>"));
	tbody.append($("<tr><td>总交易天数</td><td>" + p.getTotaltradingdays() + "</td><td>总亏损</td><td>" + p.getTotalloss() +
		"</td><td>盈利天数</td><td>" + p.getCountofwiningdate() + "</td></tr>"));
	tbody.append($("<tr><td>亏损天数</td><td>" + p.getCountoflossdate() + "</td><td>平均每天亏损</td><td>" + p.getDailyavglossamount() +
		"</td><td>MAR比率</td><td>" + p.getMarratio() + "</td></tr>"));
	tbody.append($("<tr><td>平均亏损</td><td>" + p.getAverageloss() + "</td><td>平均每天盈利</td><td>" + p.getDailyaverageprofit() +
		"</td><td>最大净值不创新高天数</td><td>" + p.getMaxlowincomeduration() + "</td></tr>"));
	$("#tbSmmary").html("").append(table);
	$("td:even", table).css("backgroundColor", "	#F5F5F5");
	$("#tabReport").parent().addClass('active').siblings().removeClass('active');
	$("#tabReportContent").addClass('active').siblings().removeClass('active');
}

function ShowChart(id, title, dates, values) {
	$('#' + id).show();
	var ct = echarts.init(document.getElementById(id));
	var option = {
		title: {
			left: 'center',
			text: title
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
				animation: false

			}
		},
		dataZoom: [{
			show: true,
			start: 0,
			end: 100
		}],
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: dates
		},
		yAxis: {
			type: 'value'
		},
		series: [{
			data: values,
			type: 'line',
			areaStyle: {}
		}]
	};
	ct.setOption(option);
}
function UpdateSingleTask(task){
	var id=task.getId();
	var state=task.getTaskStatus();
	var strategy=task.getStrategy()
	var eTask=null;
	var newStack=[];
	for(var i=0;i<TASKS.length;i++){
		if(TASKS[i].id==id){
			 TASKS[i].ele.remove();			
		}
		newStack.push(TASKS[i]);
	}
	TASKS=newStack;
	AddTask(state==2, strategy, id);
}
function AddTask(isDone, title, Id) {
	var color = isDone ? "info" : "warning";
	var strVar = "<div style=\"cursor:pointer\" class=\"bs-callout bs-callout-" + color + "\" title=\"" + title +
		"\" > <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button><strong>策略名<\/strong> " +
		title.substring(0, 12) + " ...<\/div>";
	var ele = $(strVar);
	$("span", ele).click(function() {
		event.stopPropagation();   
		if (confirm("确定要删除此回测？")) {
			removeTask(Id);
			$(this).parent().parent().remove();
			
		}
	});
	if (isDone) {
		ele.click(function() {
			initReport(Id)
		});
	} else {
		ele.click(function() {
			alert("回测进程还在执行中");
		});
	}
	$("#logs").append(ele);
	TASKS.push(
	 {
		 ele:ele,
		 id:Id,
		 isDone:isDone
	 }
	);
	if(isDone){
		showDeskMsg(initReport,Id);
	}
}
///
$(function() {
	WS = null;
	createLayout();
	connect();
	_layout.allowOverflow('north');
	$("#createDialogOptionList").children().click(function() {
		$(this).addClass("active").siblings().removeClass("active")
	});
	$('[data-datetime-picker]').each(function() {
		var $this = $(this)
		var format = $this.attr('data-datetime-picker')

		$this.datetimepicker({
			locale: 'zh-CN',
			format: format
		})
	})
	$("#datetime-start").val(20170101);
	$("#datetime-end").val(20170301);
	///////////
	$("#toLogin").click(function() {
		//Login("admin", "1");
		
		var password=$("#Password").val();
		var account=$("#UserName").val();
		
		if(account==null || account.length<1){
			alert("请输入用户名");
		}
		if(password==null || password.length<1){
			alert("请输入密码");
		}
		Login(account,password);
	});
	//the data
	showLoginDialog()
});
